// pages/conversationHistory/conversationHistory.js
Page({
  data: {
    conversations: [],
    filteredConversations: [],
    unionID: '',
    isLoading: false,
    searchValue: '',
    isSearching: false,
    showSearch: true,
    isNewUser: false // 新增标志位
  },

  onLoad() {
    wx.setNavigationBarTitle({ title: '学习记录' });
    const unionID = wx.getStorageSync('unionID') || '';
    this.setData({ unionID });

    if (!unionID) {
      console.log('conversationHistory onLoad: unionID 为空，尝试静默登录');
      const app = getApp();
      app.doAutoLogin()
        .then(() => {
          this.setData({ unionID: wx.getStorageSync('unionID') });
          this.checkNewUser();
        })
        .catch((err) => {
          console.error('静默登录失败:', err);
          this.checkNewUser();
        });
    } else {
      this.checkNewUser();
    }
  },

  onShow() {
    const unionID = wx.getStorageSync('unionID') || '';
    this.setData({ unionID });

    if (!unionID) {
      console.log('conversationHistory onShow: unionID 为空，尝试静默登录');
      const app = getApp();
      app.doAutoLogin()
        .then(() => {
          this.setData({ unionID: wx.getStorageSync('unionID') });
          this.checkNewUser();
        })
        .catch((err) => {
          console.error('静默登录失败:', err);
          this.checkNewUser();
        });
    } else {
      this.checkNewUser();
    }
  },

  checkNewUser() {
    this.loadConversations();
  },

  loadConversations() {
    this.setData({ isLoading: true });
    const baseUrl = getApp().getApiBaseUrl();
    wx.request({
      url: `${baseUrl}/conversation/get_all`,
      method: 'GET',
      data: { unionID: this.data.unionID },
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${wx.getStorageSync('jwt_token')}`
      },
      success: (res) => {
        this.setData({ isLoading: false });
        if (res.statusCode === 200 && res.data.success && res.data.titles) {
          const conversations = res.data.titles;
          this.setData({
            conversations,
            filteredConversations: conversations,
            isNewUser: conversations.length === 0
          });
          if (this.data.isNewUser) {
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/index1/index1',
                success: () => console.log('新用户跳转到 index1'),
                fail: (err) => console.error('跳转失败:', err)
              });
            }, 2000);
          }
        } else {
          wx.showToast({ title: res.data.message || '加载历史失败', icon: 'none' });
        }
      },
      fail: (err) => {
        this.setData({ isLoading: false });
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  onSearchInput(e) {
    const value = e.detail.value.trim();
    this.setData({ searchValue: value });
    this.doSearch(value);
  },

  onSearchConfirm(e) {
    const value = e.detail.value.trim();
    this.doSearch(value);
  },

  doSearch(value) {
    if (!value) {
      this.clearSearch();
      return;
    }
    const filtered = this.data.conversations.filter(item =>
      item.title.toLowerCase().includes(value.toLowerCase())
    );
    this.setData({
      filteredConversations: filtered,
      isSearching: true
    });
  },

  clearSearch() {
    this.setData({
      searchValue: '',
      filteredConversations: this.data.conversations,
      isSearching: false
    });
  },

  goToConversation(e) {
    const conversationID = e.currentTarget.dataset.conversationid;
    if (!conversationID) {
      wx.showToast({ title: '无效的对话ID', icon: 'none' });
      return;
    }
  
    console.log('goToConversation:', { conversationID });
  
    wx.setStorageSync('selectedConversationID', conversationID);
    const isExpertPath = conversationID.startsWith('expert');
    wx.setStorageSync('lastPage', isExpertPath ? 'expertConversation' : 'conversation');
  
    let targetUrl = isExpertPath
      ? `/pages/expertPath/expertConversation/expertConversation?pathID=${conversationID}`
      : `/pages/conversation/conversation?conversationID=${conversationID}`;
  
    console.log('跳转参数:', { conversationID, targetUrl });
  
    wx.showLoading({ title: '加载中...' });
    wx.reLaunch({
      url: targetUrl,
      success: () => {
        console.log(`reLaunch 到 ${targetUrl} 成功`);
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('reLaunch 失败:', err);
        wx.hideLoading();
        wx.showToast({ title: '跳转失败，请稍后重试', icon: 'none' });
        wx.removeStorageSync('selectedConversationID');
      }
    });
  },

  onShareAppMessage() {
    wx.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    });
    const baseUrl = getApp().getApiBaseUrl();
    return {
      title: '有约学习导航',
      imageUrl: `${baseUrl}/static/image/logo.png`,
      path: '/pages/home/home'
    };
  },

  onShareTimeline() {
    const baseUrl = getApp().getApiBaseUrl();
    return {
      title: '有约学习导航',
      imageUrl: `${baseUrl}/static/image/logo.png`,
      query: ''
    };
  }
});